package net.digitalartwork.ui{
	import flash.display.*;
	import flash.geom.Point;
	import flash.utils.*;
	import flash.events.*;
	import flash.net.*;
	import flash.system.LoaderContext;
	import flash.system.ApplicationDomain;
	import flash.geom.Rectangle;

	
	import net.digitalartwork.ui.TooltipThumbnail;
	import net.digitalartwork.ui.SunDraw;
	
	import com.afcomponents.umap.core.UMap; 
	import com.afcomponents.umap.overlays.Polygon;
	import com.afcomponents.umap.overlays.GroundOverlay;
	import com.afcomponents.umap.overlays.Marker;
	import com.afcomponents.umap.overlays.Layer;
	import com.afcomponents.umap.overlays.KMLLayer;
	import com.afcomponents.umap.overlays.GPXLayer;
	
 
	import com.afcomponents.umap.styles.GeometryStyle;
	import com.afcomponents.umap.styles.GradientStyle;
	import com.afcomponents.umap.styles.MarkerStyle;
	import com.afcomponents.umap.styles.StrokeStyle;
	
	import com.afcomponents.umap.styles.DropShadowStyle;
	import com.afcomponents.umap.events.OverlayEvent;
	import com.afcomponents.umap.events.MapEvent;
	import com.afcomponents.umap.events.DisplayEvent; 
	import com.afcomponents.umap.events.MapLoadEvent; 
	import com.afcomponents.umap.types.LatLng;
	import com.afcomponents.umap.types.LatLngBounds;
	import com.afcomponents.umap.types.Offset;
	import com.afcomponents.umap.types.Align;
	import com.afcomponents.umap.types.Size;
	import com.afcomponents.umap.gui.ZoomControl;
	import com.afcomponents.umap.gui.MapTypeControl;
	import com.afcomponents.umap.gui.UIMapControl;
	
	
	
	import gs.TweenFilterLite;
	import gs.easing.*;
	import com.quasimondo.geom.ColorMatrix;
	//import com.afcomponents.umap.providers.google.GoogleProvider; 
	




	public class DAMap extends Sprite{


		 var offset:Offset = new Offset(100,100);
		
		var map:UMap; // the map
		var markerlayer:Layer;
		var kml:KMLLayer;

		var myMarkers:Array = [];   //list of markers
		var myMarkersOverlay:Array = [];
		var myKMLArray:Array = [];   //list of kml
		var myGPXArray:Array = [];   //list of kml
		var currentMarker:String;
		public var current_number:Number;
		var markerColor:Number = 0x997A3D;
		var _colorselect:Number = 0x89B3CF;
		
		private var tXML:XMLList; // list of itemXML
		
		private var intervalId:uint
		
		
		public var MAP_LOADED:String = "map loaded";
		public var MARKER_CLICK:String = "markerclick";
		
		public function DAMap(w:Number, h:Number, lat:Number, lon:Number, z:Number, addType:Boolean=false) {
			
			
			function makeMap():void {
				map = new UMap();
				map.setSize(w, h);
				//map.panSpeed= 5;
				map.animatePan = true;
				map.animateZoom = true;
				map.zoomSpeed = 1;
				addChild(map);
				//--------------------------------------------------------------------------
				// Experimental Google Maps from AFCompontents
				//--------------------------------------------------------------------------
				// define GoogleProvider with custom paths
				//var settings:URLRequest = new URLRequest("settings.xml?rand=" + Math.random());
				//var language:URLRequest = new URLRequest("http://maps.google.com/maps?file=api&v=2")
				//var copyright:URLRequest = new URLRequest("http://www.afcomponents.com/proxy/g_map_as3/copyright.php");

				//map.setProvider (new GoogleProvider(false, settings, language, copyright));
				//map.setMapType("terrain");
				//map.setProvider (new GoogleProvider(false, settings, language, copyright));
				//map.setMapType("satellite");
				map.addEventListener(MapEvent.READY, ready);
				function ready(e:Event):void {
					//map.setCenter(new LatLng(36.095157,-115.001057), 8);
					map.setCenter(new LatLng(lat,lon), z);
					map.setZoom(z, true);
					//--------------------------------------------------------------------------
					// Zoom Control
					//--------------------------------------------------------------------------
					var zoom:ZoomControl = new ZoomControl();
					if (addType) {
						var maptype:MapTypeControl = new MapTypeControl()
						map.addControl(maptype);
						//map.addControl(zoom);
						zoom.align = Align.fromString("top-left");
						zoom.display = UIMapControl.DISPLAY_COMPACT;
						zoom.offset = new Point(0,0);
						zoom.padding = new Point(10,10);
					} else {
						zoom.align = Align.fromString("top-right");
						zoom.display = UIMapControl.DISPLAY_COMPACT;
						zoom.offset = new Point(0,0);
						zoom.padding = new Point(0,10);
					}

					map.addControl(zoom);
					map.doubleClickMode = "pan";
					markerlayer = new Layer();
					map.addOverlay(markerlayer);
					
					
					dispatchEvent(new Event(MAP_LOADED));
				}
				var style:MarkerStyle = new MarkerStyle();
				style.fill = GeometryStyle.RGB;
				style.fillAlpha = 0.9;
				style.strokeRGB = 0x0;
				style.strokeAlpha = 1.0;
				var timeCodeMapMarker:SunDraw = new SunDraw({shapeType:"rectangle", shapeWidth:50, shapeHeight:20, hexFill:0xFFFFFF, shapeFillAlpha:1});
				var timestyle:MarkerStyle = new MarkerStyle();
				//timestyle.icon = "timeCodeMapMarker";
				timestyle.icon = "theBox";
				//timestyle.iconStyle.align = Align.fromString("bottom-center");
				timestyle.iconStyle.scale = 1;
			}
			//--------------------------------------------------------------------------
			// EXTERNAL ASSETS
			//--------------------------------------------------------------------------
			makeMap();
			/*
			var assetLoader = new Loader();
			assetLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
			var assetContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
			var request:URLRequest = new URLRequest("da_map_assets.swf");
			assetLoader.load(request, assetContext);
			*/
			function loaded(e:Event):void {
				
				//--------------------------------------------------------------------------
				// SEARCH BOX
				//--------------------------------------------------------------------------
				//var UMap:Class = getDefinitionByName("UMapComponent") as Class;
				//var expandedtipbox = new expandedTipBox();
				//expanded_tipbox = expandedtipbox;
				//expandedMC.addChild(expanded_tipbox);
				//expanedAssetLoaded = true;
				makeMap();
			}
			
		}
		
		public function populateBox(theXML:XML):void {
			
			
			tXML = theXML.item;
			var i:int = 0;
			for each (var item in tXML) {
				makeMarkerLatLng(item.location[0], i.toString(), item.thumb[0]);
				i++;
				
			}
		}
		
		public function setMapSize(w:Number, h:Number):void {
			map.setSize(w, h);
		}
		public function addKML(kmlURL:String):void {
			// create new layer
			var kml:KMLLayer = new KMLLayer();
			kml.load(kmlURL);
			map.addOverlay(kml);
			myKMLArray.push(kml);
			
			
			
		}
		public function addGPX(gpxURL:String, gpxColor:String="0xffff00"):void {
			var gpx:GPXLayer = new GPXLayer();
			gpx.load(gpxURL);
			map.addOverlay(gpx);
			myGPXArray.push(gpx);
			//var myLine = gMap.addLine({points:linePoints, strokeThickness:10, strokeAlpha:80, strokeRGB:0x00FF00}); 
			// create new GeometryStyle & define new StrokeStyle
		 	var style:GeometryStyle = new GeometryStyle();
		 	style.fill = GeometryStyle.NONE;
		 	style.strokeThickness = 15;
		 	style.strokeRGB = 0xFFCC00; 
		 	style.strokeAlpha = 0.8;
			style.strokeStyle = new StrokeStyle();
			style.strokeStyle.jointStyle = JointStyle.BEVEL;
			style.strokeStyle.capsStyle = CapsStyle.SQUARE;

			gpx.setStyle(style);
		 	
			gpx.addEventListener(OverlayEvent.READY, overlayHandeler);
			function overlayHandeler(e:OverlayEvent):void {
				trace("GPX READY")
				gpx.removeEventListener(OverlayEvent.READY, overlayHandeler);
				TweenFilterLite.to(gpx, 1, {glowFilter:{color:gpxColor, alpha:1, blurX:5, blurY:5, strength:10}});
			}
			
		}
		public function removeMarkers():void {
			var i:int = 0;
			for (i = 0; i < myMarkers.length; i++){
				markerlayer.removeOverlay(myMarkersOverlay[i]);
				myMarkersOverlay[i].dispose();
				myMarkersOverlay[i] = null;
			}
			myMarkers = [];
			myMarkersOverlay = [];
		}
		public function makeMarker(lat:Number, lon:Number, markerName:String, theImage:String):void {
			markerColor = _colorselect;
			trace("MARKERNAME "+markerName)
			var markerExists:Boolean = false;
			for (var i = 0; i < myMarkers.length; i++){

				if (myMarkers[i].getVar() == markerName) {
					markerExists = true;
				} else {
					
				}
			}
			if (!markerExists) {
				var marker:Marker = new Marker({position: new LatLng (lat, lon), autoInfo:false, smartPosition:true, zIndexAuto:true}, timestyle);
				
				
				//marker.index = curTime;
				//marker.timecode = timeCode;
				marker.name = markerName;
				trace("marker "+marker);
				trace("marker.name "+marker.name);
				marker.description = markerName//timeCode.toString();
				var timestyle:MarkerStyle = new MarkerStyle();
				//timestyle.icon = "timeCodeMapMarker";
				//var timeCodeMapMarker:SunDraw = new SunDraw({shapeType:"rectangle", shapeWidth:50, shapeHeight:20, hexFill:0xFFFFFF, shapeFillAlpha:1});
				var timeCodeTipMarker:TooltipThumbnail = new TooltipThumbnail(0xFFFFFF,0x000000);
				//timeCodeTipMarker.showTip("00:"+Math.round(timeCode).toString())
				timeCodeTipMarker.showTip(theImage);
				//timeCodeTipMarker.holdVar("00:"+Math.round(timeCode).toString());
				timeCodeTipMarker.holdVar(markerName);
				//timestyle.icon = "rightButton.png";
				timestyle.icon = timeCodeTipMarker;
				timestyle.iconStyle.align = Align.fromString("top-left"); 
				marker.setStyle(timestyle);
				//map.addOverlay(marker);
				markerlayer.addOverlay(marker);
				marker.addEventListener(OverlayEvent.CLICK, mapMarkerUpHandeler);
				marker.addEventListener(OverlayEvent.MOUSE_DOWN, mapMarkerDownHandeler);
				marker.addEventListener(OverlayEvent.ROLL_OVER, mapMarkerOverHandeler);
				marker.addEventListener(OverlayEvent.ROLL_OUT, mapMarkerOutHandeler);
				marker.buttonMode = true; 
				marker.useHandCursor = true;


				//add marker to array
				myMarkers.push(timeCodeTipMarker);
				myMarkersOverlay.push(marker);
			}
			
			
		}
		public function makeMarkerLatLng(thePosString:String, markerName:String, theImage:String):void {
			markerColor = _colorselect;
			//trace("MARKERNAME "+markerName)
			var markerExists:Boolean = false;
			var thePos:LatLng = getLatLon(thePosString);
			for (var i = 0; i < myMarkers.length; i++){

				if (myMarkers[i].getVar() == markerName) {
					markerExists = true;
				} else {
					
				}
			}
			if (!markerExists) {
				var marker:Marker = new Marker({position:thePos, autoInfo:false, smartPosition:true, zIndexAuto:true}, timestyle);
				
				
				//marker.index = curTime;
				//marker.timecode = timeCode;
				marker.name = markerName;
				//trace("marker "+marker);
				//trace("marker.name "+marker.name);
				marker.description = markerName//timeCode.toString();
				var timestyle:MarkerStyle = new MarkerStyle();
				//timestyle.icon = "timeCodeMapMarker";
				//var timeCodeMapMarker:SunDraw = new SunDraw({shapeType:"rectangle", shapeWidth:50, shapeHeight:20, hexFill:0xFFFFFF, shapeFillAlpha:1});
				var timeCodeTipMarker:TooltipThumbnail = new TooltipThumbnail(0xFFFFFF,0x000000);
				//timeCodeTipMarker.showTip("00:"+Math.round(timeCode).toString())
				timeCodeTipMarker.showTip(theImage);
				//timeCodeTipMarker.holdVar("00:"+Math.round(timeCode).toString());
				timeCodeTipMarker.holdVar(markerName);
				//timestyle.icon = "rightButton.png";
				timestyle.icon = timeCodeTipMarker;
				timestyle.iconStyle.align = Align.fromString("top-left"); 
				marker.setStyle(timestyle);
				//map.addOverlay(marker);
				markerlayer.addOverlay(marker);
				marker.addEventListener(OverlayEvent.CLICK, mapMarkerUpHandeler);
				marker.addEventListener(OverlayEvent.MOUSE_DOWN, mapMarkerDownHandeler);
				marker.addEventListener(OverlayEvent.ROLL_OVER, mapMarkerOverHandeler);
				marker.addEventListener(OverlayEvent.ROLL_OUT, mapMarkerOutHandeler);
				marker.buttonMode = true; 
				marker.useHandCursor = true;


				//add marker to array
				myMarkers.push(timeCodeTipMarker);
				myMarkersOverlay.push(marker);
			}
			
			
		}
		private function rollOutCurrentTooltip() {
			for (var i = 0; i < myMarkers.length; i++){
				if (myMarkers[i].getVar() == currentMarker) {
					myMarkers[i].highlightTip(markerColor, 0xFFFFFF, 1.2, true);
					
				} else {
					myMarkers[i].highlightTip(0xFFFFFF, 0xFFFFFF, 1, false);
				}
			}
		}
		private function mapMarkerOverHandeler(event:Event=null):void {
			for (var i = 0; i < myMarkers.length; i++){
				if (myMarkers[i].getVar() == currentMarker) {
					myMarkers[i].highlightTip(markerColor, 0xFFFFFF, 1.2, true);
				} else {
					if (myMarkers[i].getVar() == event.target.description) {
						myMarkers[i].highlightTip(markerColor, 0xFFFFFF, 1, false);
					} else {
						myMarkers[i].highlightTip(0xFFFFFF, 0xFFFFFF, 1, false);
					}
				}
			}
		}
		private function mapMarkerOutHandeler(event:Event=null):void {
			for (var i = 0; i < myMarkers.length; i++){
				if (myMarkers[i].getVar() == currentMarker) {
					myMarkers[i].highlightTip(markerColor, 0xFFFFFF, 1.2, true);
				} else {
					myMarkers[i].highlightTip(0xFFFFFF, 0xFFFFFF, 1, false);
				}
			}
		}
		private function mapMarkerDownHandeler(event:Event=null):void {
			showCurrentTooltip(event.target.description)
			//trace(event.target.description);
			//map.panTo(event.target.position, false);
			//trace("POSITION " +event.target.position);
			current_number = event.target.name;
			dispatchEvent(new Event(MARKER_CLICK));
			
		}
		private function mapMarkerUpHandeler(event:Event):void {
			var tempPosition:Object = event.target.position;
			var tempLng:Number = tempPosition.lng;
			var tempLat:Number = tempPosition.lat;
			map.panTo(new LatLng(tempLat, tempLng));
			//map.panByXY();
			/*
			var intervalDelay:Number = 500;
			intervalId = setTimeout(delayedImageFunc, intervalDelay);
			function delayedImageFunc():void {
				clearTimeout(intervalId);
				map.panByXY(new Point(-200, 0), false); 
			}
			*/
			//map.panTo(tempPosition);
			//moveMap(tempLat, tempLng, 10)
		}
		public function showCurrentTooltip(currentPlaceName:String) {
			var tempString:String = currentPlaceName;
			for (var i = 0; i < myMarkers.length; i++){
				//trace(myMarkers[i]);
				if (myMarkers[i].getVar() == tempString) {
					currentMarker = myMarkers[i].getVar();
					myMarkers[i].highlightTip(markerColor, 0xFFFFFF, 1.2, true);
					
				} else {
					myMarkers[i].highlightTip(0xFFFFFF, 0xFFFFFF, 1, false);
				}
			}
		}
		public function moveMap(lat:Number, lon:Number, mapZoomLevelZ:Number):void {

			map.panTo(new LatLng(lat,lon),false);
			
			/*
			var intervalDelay:Number = 500;
			intervalId = setTimeout(delayedImageFunc, intervalDelay);
			function delayedImageFunc():void {
				clearTimeout(intervalId);
				map.panByXY(new Point(-200, 0), false); 
			}
			*/
			//map.setZoom(mapZoomLevelZ, false);
		}
		public function moveMapLatLng(thePosString:String, mapZoomLevelZ:Number):void {
			var thePos:LatLng = getLatLon(thePosString)
			
			map.panTo(thePos,false);
			/*
			var intervalDelay:Number = 500;
			intervalId = setTimeout(delayedImageFunc, intervalDelay);
			function delayedImageFunc():void {
				clearTimeout(intervalId);
				map.panByXY(new Point(-200, 0), false); 
			}
			 */
			//map.setZoom(mapZoomLevelZ, false);
		}
		public function zoomMap(mapZoomLevelZ:Number):void {

			map.setZoom(mapZoomLevelZ, false);
		}
		public function getCurrentMarker():Number {
			return current_number;
		}
		
		public function getLatLon(theVar:String):LatLng {
			var tempString:String = fixLatLon(theVar);
			//trace(LatLng.fromSexagecimal(tempString))
			return LatLng.fromSexagecimal(tempString);
		}
		public function fixLatLon(theVar:String):String {
			var myTextTemp:String = theVar;
			var myPatternN:RegExp = / N /gi; 
			var myPatternS:RegExp = / S /gi;
			var myPatternE:RegExp = /E/gi; 
			var myPatternW:RegExp = /W/gi;
			//--------------------------------------------------------------------------
			// Determine if string has E or W
			//--------------------------------------------------------------------------
			var eastWest:String;
			var patternEastWest:RegExp = / E /;
			if (myTextTemp.search(patternEastWest) == -1) {
				eastWest = "W";
				myTextTemp = myTextTemp.replace(myPatternW, (""));
			} else {
				eastWest = "E";
				myTextTemp = myTextTemp.replace(myPatternE, (""));
			}
			//--------------------------------------------------------------------------
			// Determine if string has N or S
			//--------------------------------------------------------------------------
			var northSouth:String;
			var patternNorthSouth:RegExp = / S /;
			if (myTextTemp.search(patternNorthSouth) == -1) {
				northSouth = "N";
				myTextTemp = myTextTemp.replace(myPatternN, (eastWest+" "));
			} else {
				northSouth = "S";
				myTextTemp = myTextTemp.replace(myPatternS, (eastWest+" "));
			}
			//--------------------------------------------------------------------------
			// Fix Quotes
			//--------------------------------------------------------------------------
			var patternSingleQuote:RegExp = /'/gi;
			myTextTemp = myTextTemp.replace(patternSingleQuote, "' ");
			var patternDoubleQuote:RegExp = /"/gi;
			myTextTemp = myTextTemp.replace(patternDoubleQuote, "'' ");
			//--------------------------------------------------------------------------
			// Fix Spaces
			//--------------------------------------------------------------------------
			var patternDegree:RegExp = /°/gi;
			myTextTemp = myTextTemp.replace(patternDegree, "° ");
			myTextTemp = northSouth + " "+myTextTemp;
			return myTextTemp;
		}
		public function colorizeMap(b:Number=-.2, s:Number=-.2, a:Number=1):void {
			var window:Rectangle = new Rectangle(0, 0, map.width, map.height);
			
			map.display.gridManager.scrollRect = window;

			TweenFilterLite.to(map.display.gridManager, .1, {alpha:a, colorMatrixFilter:{amount:1, brightness:b, saturation:s}});

			

		}
		public function colorizeOverlay():void {
			TweenFilterLite.to(map.display.gridManager, .1, {colorMatrixFilter:{amount:1, saturation:0}, alpha:.7});
			//TweenFilterLite.to(myGPXArray[0], .1, {colorMatrixFilter:{colorize:0xffff00, amount:1}, alpha:1});
			//TweenFilterLite.to(map.display.overlayManager, .1, {colorMatrixFilter:{colorize:0xffff00, amount:1}, alpha:0});
		}
	}
}




